package cn.dckeji.dcssm.controller.api;


import cn.dckeji.dcssm.common.model.ResultModel;
import cn.dckeji.dcssm.common.utils.JedisUtil;
import cn.dckeji.dcssm.common.utils.MD5;
import cn.dckeji.dcssm.common.utils.MD5Util;
import cn.dckeji.dcssm.entity.*;
import cn.dckeji.dcssm.service.*;
import cn.hutool.db.nosql.redis.RedisDS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Kenny
 * @since 2019-02-21
 */
@RestController
@RequestMapping("/api/spaceprak")
@Api(tags = "新演示管理")
public class DemoNewApi {

    @Autowired
    private DemoService demoService;

    @Autowired
    private HisService hisService;

    @Autowired
    private CountdownService countdownService;

    @Autowired
    private ParkService parkService;

    @Autowired
    private UsersService usersService;




    @PostMapping("/login")
    public ResultModel login(String userPhone, String userPwd) {
        Users users = usersService.getOne(new QueryWrapper<Users>().eq("userPhone", userPhone).eq("is_deleted",0));
        if (null==users) {
            return ResultModel.failureS("登录失败,账号或者密码不正确");
        }
        String adminLoginPassword = users.getUserPwd();
        String s = MD5Util.MD5Encode(userPwd, "utf-8");
        if (s.equals(adminLoginPassword)) {
            //登录成功
            String accessTokey = null;
            accessTokey = MD5.generateShortUuid();
            JedisUtil.setObject(accessTokey, users, 60 * 60 * 24 * 30);
            if (StringUtils.isNotBlank(users.getDeviceId())) {
                JedisUtil.del(users.getDeviceId());
            }
            users.setDeviceId(accessTokey);
            usersService.updateById(users);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("accessToken", accessTokey);
            resultMap.put("users", users);
            return ResultModel.success(resultMap);
        }
        return ResultModel.failureS("登录失败,账号或者密码不正确");
    }

    @PostMapping("/getTime")
    public ResultModel getTime() {
        Countdown aaaaaaaaaa = countdownService.getById("aaaaaaaaaa");
        String  startTime =   aaaaaaaaaa.getTimes().toString()+":00";
        String  endTime =   aaaaaaaaaa.getTimes2().toString()+":00";


        //转成LocalDateTime
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime startTime1 = LocalDateTime.parse(startTime,df);
        LocalDateTime endTime2 = LocalDateTime.parse(endTime,df);

        LocalDateTime now = LocalDateTime.now();

        Long newSecond = now.toInstant(ZoneOffset.of("+8")).toEpochMilli();//当前时间
        Long newSecond1 = startTime1.toInstant(ZoneOffset.of("+8")).toEpochMilli();//开抢时间
        Long newSecond2 = endTime2.toInstant(ZoneOffset.of("+8")).toEpochMilli();//开抢时间

        Long  newSecond2s = newSecond/1000;
        Long  newSecond12s = newSecond1/1000;
        Long  newSecond12ss = newSecond2/1000;
        Map map  = new HashMap();
        map.put("countdown",newSecond12s-newSecond2s);
        map.put("startTime",startTime);
        map.put("endcountdown",newSecond12ss-newSecond2s);
        map.put("endTime",endTime);
        return ResultModel.success(map);
    }


    @PostMapping("/getPark")
    public ResultModel getPark(String accessToken) {
        Users users = (Users) JedisUtil.getObject(accessToken);
        if (users != null) {
            List<Park> parkList = parkService.list(new QueryWrapper<Park>().eq("deleteFlag",0).orderByAsc("gmt_create"));
            List<Map> maplIst = new ArrayList<>();
            parkList.forEach(Park->{
                Map  map = new HashMap();
                String parkNo = Park.getParkNo();
                String parkNo1 = JedisUtil.get(parkNo);
                if (StringUtils.isNotBlank(parkNo1)){
                    map.put("flag",1);//已经被抢
                }else{
                    map.put("flag",0);//没有被抢
                }
                String parkPrice = Park.getParkPrice();
                map.put("parkNo",parkNo);
                map.put("parkPrice",parkPrice);
                maplIst.add(map);
            });
            return ResultModel.success(maplIst);
        }else{
            return ResultModel.failure(102,"请登录");
        }
    }

    @PostMapping("/getHis")
    public ResultModel getHis(String userId,String accessToken) {
        Users users = (Users) JedisUtil.getObject(accessToken);
        if (users != null) {
            List<His> parkList = hisService.list(new QueryWrapper<His>().eq("userId",userId));
            List<Map> maplIst = new ArrayList<>();
            parkList.forEach(his->{
                Map  map = new HashMap();
                String parkId = his.getParkId();
                Park park = parkService.getById(parkId);
                    map.put("parkNo",park.getParkNo());
                    map.put("parkPrice",park.getParkPrice());
                    map.put("times",his.getGmtCreate());
                    maplIst.add(map);
            });
            return ResultModel.success(maplIst);
        }else{
            return ResultModel.failure(102,"请登录");
        }
    }



    @PostMapping("/miaosha")
    public ResultModel miaosha(String parkNo, String userId,String accessToken) {
        Users users = (Users) JedisUtil.getObject(accessToken);
        if (users != null) {
            String userId1 = JedisUtil.get(userId);
            if(null!=userId1){
                Users u = usersService.getById(userId);
                int buNum = u.getBuyNum();
                int i = Integer.parseInt(userId1);
                if(i==buNum){
                    System.out.println("用户："+userId+"，已经抢购过了"+buNum+"车位，不能再抢购了");
                    return ResultModel.failure("您最多购买"+buNum+"车位哦!");
                }
            }
            Jedis jedis1  = JedisUtil.getResource();
            jedis1.watch(parkNo,userId);
            String redisValue = jedis1.get(parkNo);
            if (StringUtils.isBlank(redisValue)){
                Transaction transaction = jedis1.multi();
                transaction.set(parkNo,userId);
                transaction.incr(userId);
                List list = transaction.exec();
                if (list.size()!=0){
                    System.out.println("用户："+userId+"，秒杀成功！秒杀车位号"+parkNo);
                    return ResultModel.success("<div>您已成功购买车位</div><div>可到个人中心查看购买记录</div>");
                }else {
                    System.out.println("用户："+userId+"，秒杀失败！秒杀车位号"+parkNo);
                    return ResultModel.failure("<div>当前车位已被购买</div><div>请重新选择其他车位</div>");
                }
            }else {
                System.out.println(parkNo+"已经被秒杀，秒杀结束");
                return ResultModel.failure("<div>当前车位已被购买</div><div>请重新选择其他车位</div>");
            }
        }else{
            return ResultModel.failure(102,"请登录");
        }
    }



}

